package com.lhf.azkaban.springbatch.example.batchconfig;

import com.lhf.azkaban.springbatch.example.job.config.BaseConfig;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@EnableBatchProcessing
@Configuration
public class ParametersDemo extends BaseConfig implements StepExecutionListener {

    private Map<String, JobParameter> parameters;


    @Bean
    public Job parameterJob(){
                return jobBuilderFactory.get("parameterJob")
                        .start(parameterStep())
                        .build();


    }

    //job执行的是step，job使用的数据肯定是在step中；
    //我们只需要给step传递数据；
    //如何给step传递参数；我们可以使用step级别的监听来传递数据
    @Bean
    public Step parameterStep() {
        return stepBuilderFactory.get("parameterStep")
                .listener(this)
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                        System.out.println(parameters.get("info"));
                        return RepeatStatus.FINISHED;
                    }
                }).build()
                ;
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        parameters=stepExecution.getJobParameters().getParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }
}
